﻿// CThread.cpp: 实现文件
//

#include "pch.h"
#include "MFC.h"
#include "CThread.h"


// CThread

IMPLEMENT_DYNCREATE(CThread, CWinThread)

CThread::CThread()
{
}

CThread::~CThread()
{
}

BOOL CThread::InitInstance()
{
    // TODO:    在此执行任意逐线程初始化

    HRESULT hResult;
    BOOL bOpen = FALSE;
    IStorage* lpIStorage = nullptr;
    IStream* lpIStream = nullptr;
    PWCHAR lpString = L"HelloWOrld";
    ULONG nLength = wcslen(lpString) * sizeof(WCHAR) + sizeof(WCHAR);
    LARGE_INTEGER lgLength = { 0 };
    lgLength.QuadPart = nLength;

    hResult = ::StgCreateStorageEx(L"E:\\FILE.bin", STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, 0,
        nullptr, nullptr, IID_IStorage, (void**)&lpIStorage);
    if (hResult == STG_E_FILEALREADYEXISTS)
    {
        hResult = ::StgOpenStorageEx(L"E:\\FILE.bin", STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, 0,
            nullptr, nullptr, IID_IStorage, (void**)&lpIStorage);
    }

    if (lpIStorage)
    {
        hResult = lpIStorage->CreateStream(L"STREAM.txt", STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 
            0, 0, &lpIStream);
        if (hResult == STG_E_FILEALREADYEXISTS)
        {
            hResult = lpIStorage->OpenStream(L"STREAM.txt", nullptr,
                STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, &lpIStream);
            bOpen = TRUE;
        }

        if (lpIStream)
        {
            if (bOpen)
                lpIStream->Seek(lgLength, STREAM_SEEK_SET, nullptr);

            hResult = lpIStream->Write(lpString, nLength, nullptr);
            lpIStream->Commit(STGC_DEFAULT);
            lpIStream->Release();
        }

        lpIStorage->Commit(STGC_DEFAULT);
        lpIStorage->Release();
    }

    return FALSE;   //	返回FALSE，否则会进入消息循环，线程退不出，调用不了ExitInstance
}

int CThread::ExitInstance()
{
	// TODO:    在此执行任意逐线程清理
	return CWinThread::ExitInstance();
}

BEGIN_MESSAGE_MAP(CThread, CWinThread)
END_MESSAGE_MAP()


// CThread 消息处理程序
